package com.zhubayi.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.zhubayi.constant.MyConstant;
import com.zhubayi.entity.Admin;
import com.zhubayi.entity.R;
import com.zhubayi.entity.VerifyCode;
import com.zhubayi.entity.vo.UserVo;
import com.zhubayi.service.AdminService;
import com.zhubayi.service.IVerifyCodeService;
import com.zhubayi.service.UserService;
import com.zhubayi.service.VideoService;
import com.zhubayi.utils.UserQueryConditionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 祝八一
 */
@Controller
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    IVerifyCodeService codeService;
    @Autowired
    UserService userService;
    @Autowired
    VideoService videoService;
    private VerifyCode generate=null;
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        Object admin = session.getAttribute("admin");
        if (admin!=null){
            session.removeAttribute("admin");
        }
        return "redirect:tologin";
    }
    @GetMapping({"/","index"})
    public String index(HttpServletRequest request,Model model){
        HttpSession session = request.getSession();
        Admin admin =(Admin) session.getAttribute("admin");
        if (admin!=null){
            model.addAttribute("admin",admin);
        }
        return "admin/index";
    }
    @GetMapping("welcome")
    public String welcome(){
        return "admin/welcome";
    }
    @RequestMapping("/tologin")
    public String toLogin(){
        return "admin/login";
    }
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(RedirectAttributes redirectAttributes,HttpSession session, @RequestParam String account, @RequestParam String password, @RequestParam String code, Model model) throws IOException {
        String generateCode = this.generate.getCode();
        if (!generateCode.equalsIgnoreCase(code)){
            model.addAttribute("msg","验证不对");
            return "admin/login";
        }
        else {
            Admin admin = new Admin();
            admin.setAccount(account);
            admin.setPassword(password);
            System.out.println(admin);
            if(adminService.login(admin)){
                this.generate = codeService.generate(80, 28);
                //添加到session中
                session.setAttribute("admin",admin);
                redirectAttributes.addFlashAttribute("admin",admin);

                return "redirect:/admin/";
            }else {
                model.addAttribute("msg","用户或密码不对");
                return "admin/login";
            }
        }

    }
    @ResponseBody
    @RequestMapping("safecode")
    public byte[] safecode() throws IOException {
        this.generate = codeService.generate(80, 28);
        return  this.generate.getImgBytes();
    }
    @RequestMapping("toupdatepwd")
    public String toupdatepwd(){
        return "admin/pwd_update";
    }
    @RequestMapping("updatepwd")
    public String updatepwd(@RequestParam String oldpwd,@RequestParam String newpwd,Model model){
        if (adminService.CheckOldPwd(1,oldpwd)){
            //原密码对
            adminService.updatePassword(1,newpwd);
            model.addAttribute("msg","修改成功");
        }
        else {
            //原密码不对
            model.addAttribute("msg","原密码不对");

        }
        return "admin/pwd_update";
    }

    @RequestMapping("toUser")
    public String toUser(UserQueryConditionUtils utils, Model model, @RequestParam(required = false) Integer currentPage, String time, @RequestParam(required = false)Integer pageSize) {
        if (currentPage == null || currentPage < 0) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 3;
        }
        //只有紧跟在PageHelper.startPage方法后的第一个Mybatis的查询（Select）方法会被分页。
        //开启分页
        // List<VideoVo> videoVoList = videoService.getAll();
        //PageHelper.startPage(currentPage, pageSize).setOrderBy("id desc");
        PageInfo<UserVo> usersPage = null;
        if (StringUtils.isEmpty(utils.getEmail()) && StringUtils.isEmpty(utils.getUsername())) {
            usersPage = userService.queryAll(currentPage, pageSize);
        }else {
            usersPage=userService.queryCondition(utils,currentPage, pageSize);

        }
            model.addAttribute("usersPage", usersPage);
            model.addAttribute("queryCondition", utils);
            return "admin/user_table";

    }
    @ResponseBody
    @PostMapping(value = "/downloadUser")
    public void download(HttpServletResponse response, @RequestBody String vo) throws IOException {
        List<UserVo> userVoList = JSON.parseArray(vo, UserVo.class);
        userService.download(response,userVoList);

    }
    @RequestMapping("tongji")
    public String tongji(){
        return "admin/tongji";
    }
    @ResponseBody
    @GetMapping("tongjiData")
    public R tongjidata(){
        Map<String,Integer> data=videoService.getCategoryVideoNum();
        return new R(MyConstant.OK,data);
    }
       @ResponseBody
    @GetMapping("tongjiData2")
    public R tongjidata2(){
        Map<String,Integer> data=videoService.getSortByViewNum();
        return new R(MyConstant.OK,data);
    }
    @ResponseBody
    @GetMapping("tongjiData3")
    public R tongjidata3(){
        Map<String,Integer> data=videoService.getSortByPraiseNum();
        return new R(MyConstant.OK,data);
    }
    @ResponseBody
    @GetMapping("tongjiData4")
    public R tongjidata4(){
        Map<String,Integer> data=videoService.queryPubTime();
        return new R(MyConstant.OK,data);
    }

}
